<?php

declare(strict_types=1);

namespace app\admin\middleware;
use think\facade\Log;
use app\utils\Redis as RedisDB;

class CheckPermi
{
    /**
     * 验证权限
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取Authorization

        try {
            $permission = $request->rule()->getOption('permission');
            if (!$permission) {
                return $next($request);
            }
            $uRedis = new RedisDB('user');
            $pRedis = new RedisDB('perms');
            $uid = $request->uid;
            $userRole = $uRedis->hGetAll('role:' . $uid);
            $rolesId = array_values($userRole);
            $perms = [];
            if (!in_array('1', $rolesId)) {
                foreach ($rolesId as $role) {
                    $perms[] = 'perms:roleId:' . $role;
                }
                $res = $pRedis->sUnion($perms);
                if (in_array($permission, $res)) {
                    return $next($request);
                } else {
                    return error('暂无该权限，请联系管理员', '403');
                }
            } else {
                return $next($request);
            }
        } catch (\Throwable $e) {
            return error('暂无该权限，请联系管理员', '403');
        }
    }

}
